from rest_framework.views import exception_handler as drf_exception_handler
from utils.loggers import log_uru
from utils.common_response import APIResponse

from rest_framework.exceptions import AuthenticationFailed, ValidationError
from django.http import Http404
from django.db.utils import IntegrityError

code_dict = {
    # 认证失败
    AuthenticationFailed: 401,
    # 字段校验失败
    ValidationError: 402,
    # 字段值重复
    IntegrityError: 403,
    # 页面未找到
    Http404: 404
}


def exception_handle(exc, context):
    request = context.get('request')
    view = context.get('view')
    ip = request.META.get('REMOTE_ADDR')
    user_id = request.user.id or '【匿名用户】'
    log_uru.error(
        f'{view.get_view_name()}|{str(exc)}|ip地址为：{ip}|用户{user_id}')
    # 先执行drf自带的异常捕获
    res = drf_exception_handler(exc, context)
    if res:
        # print(res.data)
        # drf的异常 data=['错误1',错误2]    data={detail:'sss'}
        if isinstance(res.data, dict):
            err = ''.join([f'【{key}|{value[0]}】-' for key, value in res.data.items()])
            # err = res.data.get('detail')
        elif isinstance(res.data, list):
            print(res.data)
            err = res.data[0]
        else:
            err = 'drf服务异常，请稍后再尝试'
        response = APIResponse(999, msg=err)
    else:
        # 非drf异常，更细力度的区分异常
        code = code_dict.get(exc.__class__) or 989
        # print(exc)
        response = APIResponse(code, msg=str(exc))
    return response
